//uses jquery
//uses services/flickr.js
//uses fancybox

var kavadenn = kavadenn || {};

kavadenn.PhotoAlbumApplication = function(community,settings){
  var defaultSettings = {};
  var _settings = {};
  $.extend(_settings, defaultSettings, settings);
  
  this.getSetting = function(key) { return _settings[key]; }
  
  this.community = community;
  
  this.generalFlickrSearch = null;
  this.currentUserFlickrSearch = null;
  
  //a list of small thumb urls that that  
  this.__pictureUrls = [];
}

kavadenn.PhotoAlbumApplication.prototype.hasImage = function(thumbUrl){
  return -1 != jQuery.inArray(thumbUrl, this.__pictureUrls);
}

kavadenn.PhotoAlbumApplication.prototype.initialize = function(){
  this.initializeUI();
  
  //enumerate available images
  $("#kavadenn-images-pane > ul > li").each(
    this._bindCallback(function(index,e) {
      this.__pictureUrls.push($(e).find("center > a > img").attr("src"));
  }));
  try{console.log(this.__pictureUrls);}catch(x){}
  
  this.generalFlickrSearch = new kavadenn.FlickrRequest(
      {"text":this.community + ", Bretagne"},
      this._bindCallback(function(d){
        if(this.generalFlickrSearch.hasMore()) 
          $("#more-images-button").show().removeAttr("disabled");
        else $("#more-images-button").attr("disabled","disabled");
        this.renderImages(d,$("#flickr-images-pane > ul"));
  }),{"exclude_list":this.__pictureUrls});
  this.generalFlickrSearch.execute();
}

kavadenn.PhotoAlbumApplication.prototype.initializeUI = function(){
   $("ul.tabs").tabs("div.panes > div");
  
   $("#flickr-connect-button").click(function(){
      $(this).html("connexion en cours...");
      $(this).attr("disabled","disabled");
      flickrAuth();
   }); 
  
   $("#more-images-button").click(this._bindCallback(function(){
      if(!this.generalFlickrSearch)return;
      if(this.generalFlickrSearch.hasMore()){
        $("#more-images-button").attr("disabled","disabled");
        this.generalFlickrSearch.execute();
      } 
        
   }));
   
   $("#more-user-images-button").click(this._bindCallback(function(){
      if(!this.currentUserFlickrSearch)return;
      if(this.currentUserFlickrSearch.hasMore()){
        $("#more-user-images-button").attr("disabled","disabled");
        this.currentUserFlickrSearch.execute();
      } 
        
   }));
  
   $(".photo-thumb-link").click(this.handlePhotoSelection);
   
   $("#backToGalleryBtn").click(function(){
     $("#photoPane").hide();
     $("#photoGallery").show();
   });
}

kavadenn.PhotoAlbumApplication.prototype.runCurrentUserFlickrSearch = function(){
  this.currentUserFlickrSearch = new kavadenn.FlickrRequest({"search_type" : "user_photos"},
      this._bindCallback(function(d){
        if(this.currentUserFlickrSearch.hasMore()) 
          $("#more-user-images-button").show().removeAttr("disabled");
        else $("#more-user-images-button").attr("disabled","disabled");
        this.renderImages(d,$("#flickr-user-images-pane > ul"));
      }),{"exclude_list":this.__pictureUrls});
  this.currentUserFlickrSearch.execute(); 
}

kavadenn.PhotoAlbumApplication.prototype.renderImages = function(images,targetContainer){
    try{console.log(images);}catch(x){} 
    var imgPane = targetContainer;
    
    $.each(images,function(index,i){
      imgPane.append(
        $("<li></li>").append(
          $("<img />").attr("src",i.thumb) 
        ).wrapInner("<center></center>").append(
          $("<a></a>").attr("class","gallery-image-zoom").attr("rel",i.medium).attr("title",i.title).append(
            $("<img />").attr("src","/static/img/wires/photos/zoom.png"))
          ).append(
          $("<a></a>").attr("class","gallery-image-add").attr("rel",i.medium).data("image-meta",i).append(
            $("<img />").attr("src","/static/img/wires/photos/add-photo.png")
          )));
      
    });
    
    $(".gallery-image-zoom").click(function(){
       var link = $(this);
       $.fancybox({
          'titleFormat': function(title, currentArray, currentIndex, currentOpts) {
              return link.attr("title");
          },
          'titlePosition': 'inside',
          'href': $(this).attr("rel"),
          'autoDimensions'  : true,
          'transitionIn'    : 'none',
          'transitionOut'   : 'none'
        }); 
     });
    
    $(".gallery-image-add").click(this._bindCallback(function(e){
      var link = $(e.currentTarget);
      var image_meta = link.data("image-meta");
      var thumb_url = image_meta["thumb"];
      image_meta["community_id"] = this.community;
      link.hide();
      
      if(this.hasImage(thumb_url)) return;
      this.__pictureUrls.push(thumb_url);
      
      $.post("/photos/add/",image_meta,this._bindCallback(function(d){
          if(d.status == "ok"){
            var imageContainer = link.parent(); 
            imageContainer.fadeOut('fast', this._bindCallback(function() {
              var img = imageContainer.detach();
              img.appendTo("#kavadenn-images-pane > ul");
              img.children(".gallery-image-add").remove();
              img.children(".gallery-image-zoom").remove();
              img.find("img").wrap($("<a class='photo-thumb-link'>").attr("rel",d.id).click(this.handlePhotoSelection));
              
              img.fadeIn('fast');
            }));
            
            try{ console.log(this.__pictureUrls);}catch(x){}
        }
      }));
    }));
     
    $("body").animate({scrollTop: $("body").height()}, 250);
}

kavadenn.PhotoAlbumApplication.prototype.handlePhotoSelection = function(e) {
  $("#photoGallery").hide();
  $("#photoPane").show();
  
  $("#photoPaneContent").load("/photos/get/" + $(e.currentTarget).attr("rel"));
}

kavadenn.PhotoAlbumApplication.prototype._bindCallback = function(callback) {
    //utility method to bind callback methods to the object instance
    var objSelf = this;
    return (function() { return (callback.apply(objSelf, arguments)); });
}